package cn.icanci.loopstack.ddk.admin.biz.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.icanci.loopstack.ddk.admin.biz.service.IDGeneratorService;
import cn.icanci.loopstack.ddk.admin.biz.utils.IDHolder;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

/**
 * 分布式ID生成器
 * 
 * @author icanci
 * @since 1.0 Created in 2022/10/30 08:43
 */
@Service
public class IDGeneratorServiceImpl implements IDGeneratorService, InitializingBean {
    /** 雪花序列号生成算法 */
    private static final Snowflake SNOW_FLAKE = new Snowflake(RandomUtils.nextInt(1, 9), RandomUtils.nextInt(1, 9));

    private static final String    DDK_PREFIX = "DDK";

    @Override
    public String generateBySnowFlake(String prefix) {
        return prefix + SNOW_FLAKE.nextId();
    }

    @Override
    public String generateBySnowFlakeForDdk() {
        return generateBySnowFlake(DDK_PREFIX);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        IDHolder.setIdGeneratorService(this);
    }
}
